package com.tgy.programmer_code_interview_guide._01_stack_queue;

import java.util.Stack;

/** @Author: tgy @Date: 1/18/21 1:52 PM */
public class _03_仅用递归函数和栈操作逆序一个栈 {

    private int getAndRemoveLastElement(Stack<Integer> stack) {

        Integer top = stack.pop();

        if (stack.isEmpty()) {

            return top;
        } else {

            int result = getAndRemoveLastElement(stack);
            stack.push(top);
            return result;
        }
    }

    private void reversal(Stack<Integer> stack) {

        if (stack.isEmpty()) {
            return;
        }

        int lastElement = getAndRemoveLastElement(stack);
        reversal(stack);
        stack.push(lastElement);
    }

    public static void main(String[] args) {

        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < 6; ++i) {

            stack.push(i+1);
        }

        new _03_仅用递归函数和栈操作逆序一个栈().reversal(stack);

        while (!stack.isEmpty()) {

            System.out.println(stack.pop());
        }
    }
}
